//
//  MMSegmentHeader.swift
//  MMSegmentHeader
//
//  Created by huangweiqiang on 2022/6/24.
//

import UIKit

enum MMSegmentHeadStyle {
    /**
     *  默认
     */
    case SegmentHeadStyleDefault
    /**
     *  line(下划线)
     */
    case SegmentHeadStyleLine
    /**
     *  arrow(箭头)
     */
    case SegmentHeadStyleArrow
    /**
     *  Slide(滑块)
     */
    case SegmentHeadStyleSlide
}

enum MMSegmentLayoutStyle {
    /*
     * 默认均分(如果说所有的title宽度大于一屏宽度，则自动放大每一个item)
     */
    case layoutDefault
    /*
     * 居左（自适应靠左）
     */
    case layoutLeft
    /*
     * 居中(标题不足一屏时,用一屏展示)
     */
    case layoutCenter
}

struct MMenuConfig {
    var segment_height: CGFloat = 44
    var segment_line_height: CGFloat = 2
}

class MMSegmentHeader: UIView {
    var config: MMenuConfig!
    var titleArray: [String] = []
    var collectionView: UICollectionView!
    var showIndex: NSInteger = 0
    var bottomLineView: UIView!
    var selectIndex:((NSInteger)->Void)?
    var selectFlag: Bool = true //点击不是滑动标识
    var endScale: CGFloat = 0;
    var layoutStyle: MMSegmentLayoutStyle = .layoutDefault
    var maxTitleWidth: CGFloat = 0
    var disMinWidth: CGFloat = 0 //所有title总和的宽度与设备宽度之差
    class func initSegmentHeader(frame: CGRect, titles: [String], config: MMenuConfig? = nil, headStyle: MMSegmentHeadStyle, layoutStyle: MMSegmentLayoutStyle) -> MMSegmentHeader {
        let header = MMSegmentHeader.init(frame: frame)
        header.layoutStyle = layoutStyle
        header.config = config ?? MMenuConfig()
        header.titleArray = titles
        return header
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func defaultAndCreateView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        collectionView = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
        collectionView.register(MenuViewItemCell.self, forCellWithReuseIdentifier: "MenuViewItemCell")
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsHorizontalScrollIndicator = false
        self.addSubview(collectionView)
        
        let fir_width = self.getLabelWidth(str: self.titleArray.first!)
        bottomLineView = UIView.init(frame: CGRect.init(x: fir_width/2 - 28/2, y: self.bounds.size.height - self.config.segment_line_height, width: 28, height: self.config.segment_line_height))
        bottomLineView.backgroundColor = UIColor.blue
        bottomLineView.isHidden = false
        bottomLineView.layer.cornerRadius = 2
        bottomLineView.layer.masksToBounds = true
        self.collectionView.addSubview(bottomLineView)
        
        
        
//        if self.layoutStyle == .layoutDefault {
//            ///去判断够不够一屏宽度，如果不足则修改item的宽度，二次刷新
//            self.layoutStyle = .layoutLeft //选用自适应的style去计算宽度
//            collectionView.reloadData()
//            collectionView.layoutIfNeeded()
//            let tempW = collectionView.collectionViewLayout.collectionViewContentSize.width
//            if tempW < kScreenWidth {
//                self.disMinWidth = kScreenWidth - tempW
//                self.layoutStyle = .layoutDefault
//                self.collectionView.reloadData()
//            }
//            let tempFir_w = self.getLabelWidth(str: self.titleArray.first!)
//            bottomLineView.center.x = tempFir_w/2
//        }
        
//        if self.layoutStyle == .layoutDefault {
//            let max_width = self.getMaxTitleWidth()
//            if max_width > kScreenWidth/CGFloat(self.titleArray.count) {
//                //说明均等分时，宽度不够放，则采用靠左的方式展示
//                //self.disMinWidth = max_width - kScreenWidth/CGFloat(self.titleArray.count)
//                self.layoutStyle = .layoutLeft
//                self.collectionView.reloadData()
//            }
//            let tempFir_w = self.getLabelWidth(str: self.titleArray.first!)
//            bottomLineView.center.x = tempFir_w/2
//        }
    }
    
    ///获取title的宽度
    func getLabelWidth(str: String) -> CGFloat {
        switch self.layoutStyle {
        case .layoutLeft:
            //靠左
           return self.calculatorTitleWidth(str: str)
        case .layoutDefault:
            //默认均等分
            return kScreenWidth/CGFloat(self.titleArray.count)
            //center
        default:
            return kScreenWidth/CGFloat(self.titleArray.count)
        }
       
    }
    
    ///获取所以title中最大的宽度
    func getMaxTitleWidth() -> CGFloat {
        var tempW: CGFloat = 0
        for itemStr in self.titleArray {
            let aWidth = self.calculatorTitleWidth(str: itemStr)
            if tempW < aWidth {
                tempW = aWidth
            }
        }
        return tempW
    }
    
    ///计算标题宽度
    private func calculatorTitleWidth(str: String) -> CGFloat {
        let size = CGSize(width:1000, height:20)
        let dic = NSDictionary(object: UIFont.init(name: Theme.PingFangSCRegular, size: 14)!, forKey: kCTFontAttributeName as! NSCopying)
        let strSize = str.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : Any] , context: nil).size
//        let ww = XTManageCenter.getLabWidth(labelStr: str, font: UIFont.init(name: Theme.PingFangSCRegular, size: 14)!, height: 44)
        return strSize.width + 22
    }
    
    
    override func layoutSubviews() {
        self.collectionView.frame = self.bounds
        print("执行了 layoutSubviews")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///
    func changeCurrentIndex(index: NSInteger, completed: Bool) {
        if self.showIndex == index {
            return
        }
        
        let tempRect = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath.init(row: index, section: 0))
        let offsetX = (tempRect?.size.width ?? 0)/2 + (tempRect?.frame.origin.x ?? 0)
        UIView.animate(withDuration: 0.18, delay: 0, options: .curveEaseInOut) {
            self.bottomLineView.center.x = offsetX
        } completion: { flag in
            //
        }
        self.showIndex = index
        self.collectionView.reloadData()
        self.collectionView.scrollToItem(at: IndexPath.init(row: index, section: 0), at: .centeredHorizontally, animated: true)
    }
    
    
    ///监听SegmentScroll的offsetx
    func addObserverSegmentScrollViewDidScrollToPoint(offsetx: CGFloat) {
        if self.selectFlag {
            self.selectFlag = false
            return
        }
        let scale = offsetx/(CGFloat(kScreenWidth) * CGFloat(self.titleArray.count))
        if scale < 0 {
            return
        }
        let left = endScale > scale
        endScale = scale
        
        let pre_view = 1.0/CGFloat(self.titleArray.count)
        let changeIndex: NSInteger = NSInteger(scale/pre_view + (left ? 1 : 0))
        let nextIndex: NSInteger  = changeIndex + (left ? -1 : 1)
        if (nextIndex >= self.titleArray.count) || (changeIndex >= titleArray.count) {
            return
        }
        
        let sum_width: CGFloat = self.collectionView.collectionViewLayout.collectionViewContentSize.width
        
        let changeRect = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath.init(row: changeIndex, section: 0))
        let nextRect = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath.init(row: nextIndex, section: 0))
        let start_scale = nextRect?.frame.origin.x
        
        //滑动选中位置所占的相对百分比
        let current_title_Scale: CGFloat = (changeRect?.frame.size.width ?? 0)/sum_width
        
        //单个view偏移的百分比
        let single_offset_scale: CGFloat = (scale - pre_view*CGFloat(changeIndex))/pre_view
        
        let titleScale = single_offset_scale * current_title_Scale + start_scale!
        
        let change_scale = (left ? CGFloat(-1) : CGFloat(1))*(titleScale - start_scale!)/current_title_Scale;
        let change_center = nextRect!.center.x - changeRect!.center.x
        let center_x = changeRect!.center.x + change_scale * change_center
        self.bottomLineView.center.x = center_x
    }
    
    ///选中header的下标
    func setSelectHeaderAtIndex(index: NSInteger) {
        if index == self.showIndex {
            return
        }
        self.showIndex = index
        let selectCell = collectionView.cellForItem(at: IndexPath.init(row: index, section: 0)) as? MenuViewItemCell
        if selectCell != nil {
            let offsetX = (selectCell?.frame.size.width ?? 0)/2 + (selectCell?.frame.origin.x)!
            UIView.animate(withDuration: 0.18, delay: 0, options: .curveEaseInOut) {
                self.bottomLineView.center.x = offsetX
            } completion: { flag in
                //
            }
        }
        self.collectionView.reloadData()
        self.collectionView.scrollToItem(at: IndexPath.init(row: index, section: 0), at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
        self.selectIndex?(self.showIndex)
    }
}


extension MMSegmentHeader: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.1
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.1
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let tempStr = self.titleArray[indexPath.row]
        return CGSize.init(width: self.getLabelWidth(str: tempStr), height: 44)
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.titleArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MenuViewItemCell", for: indexPath) as! MenuViewItemCell
        cell.titleLab.text = self.titleArray[indexPath.row]
        
        if self.showIndex == indexPath.row {
            cell.titleLab.textColor = Theme.mainColor
        }else{
            cell.titleLab.textColor = Theme.titleLabColor
        }
        cell.titleLab.frame = cell.bounds
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.showIndex = indexPath.row
        let selectCell = collectionView.cellForItem(at: indexPath) as? MenuViewItemCell
        if selectCell != nil {
            let offsetX = (selectCell?.frame.size.width ?? 0)/2 + (selectCell?.frame.origin.x)!
            UIView.animate(withDuration: 0.18, delay: 0, options: .curveEaseInOut) {
                self.bottomLineView.center.x = offsetX
            } completion: { flag in
                //
            }
        }
        
        self.collectionView.reloadData()
        self.collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
        self.selectFlag = true
        self.selectIndex?(self.showIndex)
    }
}


class MenuViewItemCell: UICollectionViewCell {
    var titleLab: UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        titleLab = UILabel.init(frame: self.bounds)
        titleLab.backgroundColor = UIColor.clear
        titleLab.textAlignment = .center
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        titleLab.textColor = UIColor.black
        self.contentView.addSubview(titleLab)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

